/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var maxNumberOfTab = 5;
var activeChat;
var delay = 500;
//var roomId = 1;
var intervalAjax;
var t = null;

function initAjax(roomId) {
    showChat(roomId);
    t = setInterval(showChat, 1000, roomId);
}

function ajax(file,fungsi){
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }
    else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = fungsi;
    xmlhttp.open("GET",file,true);
    xmlhttp.send();
}

function createNewTab(usersession, userdestination,roomId) {
    var roomName = usersession+userdestination;
    var roomDescr = "chatting" + usersession + "and" + userdestination;
    //create room
    ajax("../controller/createRoom.jsp?roomName="+roomName+"&roomTipe=1&roomDescr="+roomDescr);
    //add chatter to room
    ajax("../controller/addChatterToRoom.jsp?roomId="+roomId+"&name="+usersession);
    ajax("../controller/addChatterToRoom.jsp?roomId="+roomId+"&name="+userdestination);
}

function deleteTab(roomId) {
    ajax("../controller/disposeRoom.jsp?roomId="+roomId);
}

function showTab() {

}

function tabClick(name) {
    /*var ajax = new AjaxWrap();
    ajax.onLoadSuccess = function(ajax) {
        var newcontent = document.getElementById("chatArea");
        newcontent.innerHTML = "halo"//ajax.xhr.responseText;
    }*/
    var newcontent = document.getElementById("chatArea");
    newcontent.innerHTML = "halo";
    
}

function isACommand(message) {
    var regex = /^[/]/;
    return regex.test(message);
}

function postMsg(message,roomId) {
    if(isACommand(message)){
        ajax("../controller/commandParser.jsp?com="+message,function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                alert(xmlhttp.responseText);
            }
        });
    }
    else{
        ajax("../controller/postChat.jsp?message="+message+"&roomId="+roomId,function(){});
        //showChat(roomId);
    }
    var abc = document.getElementById("ChattoPost");
    abc.value = "";
}

function showChat(roomId) {
    var xmlhttp;
    if (window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }
    else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            document.getElementById("chatArea").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","../controller/showChat.jsp?roomId="+roomId,true);
    xmlhttp.send();
}